
import { createRouter, createWebHashHistory } from 'vue-router';
import { getToken } from '../utils/unit'
import store from '../store/index'
/**
 * 静态路由 容器
 */
const defaultRouter = [
    {
        name: 'login',
        path: '/login',
        component: () => import('../views/login/login.vue'),

    },
    {
        name: 'index',
        path: '/index',
        redirect:'/index/homepage',
        component: () => import('../views/index/index.vue'),
        children:[
            {
                name:'homepage',
                path:'homepage',
                component: () => import('../views/index/homepage.vue'),
            }
        ],
        // meta: {
        //     title: '首页'
        // }
    },
];

const router = createRouter({
    scrollBehavior: () => ({ y: 0 }),
    routes: defaultRouter,
    history: createWebHashHistory()
})
const getAsyncRouters = () => {
    const menus = store.getters.getNewMenus;
    //生成路由信息
    for (let i = 0; i < menus.length; i++) {
        const firstmenu = menus[i];
        const newRouter = {
            name: firstmenu.name,
            path: '/' + firstmenu.name,
            component: () => import('../views/index/index.vue'),
            redirect:'/index',
            meta: {
                title: firstmenu.title
            },
            children: []
        }
        for (let j = 0; j < firstmenu.children.length; j++) {
            const secondmenu = firstmenu.children[j];
            newRouter.children.push(
                {
                    name: secondmenu.name,
                    path: secondmenu.name,
                    meta: {
                        title: secondmenu.title
                    },
                    component: () => import(`../views/${firstmenu.name}/${secondmenu.name}.vue`),
                }
            )

        }
        router.addRoute(newRouter)
    }
}

router.beforeEach((to, from, next) => {
    const token = getToken();
    if (!token && to.path != '/login') {
        next('/login')
    } else if (token && store.state.userStore.menus.length === 0) {
        console.log('menus为空');
        store.dispatch('getUserInfo').then(() => {
            getAsyncRouters()
            //为什么加to因为动态生成路由后如果要进入的页面是动态生成的路由页面，需要再跳一次
            next(to)
        }
        )
    } else if (token && store.state.userStore.menus.length !== 0 && from.path === '/login' && to.path === '/index') {
        // 动态添加路由规则
        getAsyncRouters();
        next();
    } else if (token && to.path === '/login') {
        next(from);
    } else if (token && to.path === '/') {
        next('/index')
    }
    else {
        next()
    }

})
export default router;
